package com.nitty.cash.loop.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.tabs.TabLayout
import com.lib.common.adapter.CommonOnItemChildClickListener
import com.lib.common.adapter.CommonRecyclerViewAdapter
import com.lib.common.adapter.CommonViewHolderHelper
import com.nitty.cash.loop.NittyApp
import com.nitty.cash.loop.R
import com.nitty.cash.loop.common.CommonDialog
import com.nitty.cash.loop.databinding.DialogBirthdayBinding
import com.nitty.cash.loop.databinding.DialogBirthdayMonthItemBinding
import com.nitty.cash.loop.event.NittyEventPointHelper
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.utils.NittyDensityUtil
import com.nitty.cash.loop.utils.decoration.GridSpacingItemDecoration
import com.nitty.cash.loop.utils.helper.NittyDateHelper
import com.nitty.cash.loop.weight.font.MediumTextView
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Calendar

/**
 * Author : wwdeng
 * Date : 2024/5/23 15:44
 * <p>
 * 每天进步一点点
 * <p>
 * Desc : 流程选择出生日期
 */
class NittyBirthdayDialog: CommonDialog {
    private lateinit var binding: DialogBirthdayBinding
    private var mCallback: IDialogCallback? = null
    //开始选择时间
    private var startTime = 0L;
    //事件备注
    private var eventRemark = ""
    /* 周 */
    private var weekAdapter: WeekAdapter? = null
    /* 日期 */
    private var mDayAdapter: DayAdapter? = null

    //年
    private var showYear = NittyDateHelper.getCurtYear()
    //月
    private var isInit = true
    private var showMonth = NittyDateHelper.getCurtMonth()
    //日
    private var showDay = NittyDateHelper.getCurtDay()

    constructor(context: Context) : super(context) {}
    constructor(context: Context, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    constructor(context: Context, remark: String,callback: IDialogCallback?) : super(context) {
        mCallback = callback
        eventRemark = remark
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback){
        this.mCallback = callback
    }

    override fun initWindow() {
        val params = window!!.attributes
        params.width = NittyApp.app.getPhoneWidth()
        params.height = WindowManager.LayoutParams.WRAP_CONTENT
        window!!.attributes = params
        window!!.setWindowAnimations(R.style.dialog_slide_anim) //修改动画样式
        window!!.setGravity(Gravity.BOTTOM)
    }

    override fun getRootView(): View {
        binding = DialogBirthdayBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initView() {
        initMonthTabLayout()
        initRvWeek()
        initRvDay()
    }

    override fun initListener() {
        setOnClickListener(binding.btnDone)
        //上一年
        binding.imgLastYear.setOnClickListener {
            showYear--
            showYear()
            showDay()
        }
        //下一年
        binding.imgNextYear.setOnClickListener {
            if (showYear >= NittyDateHelper.getCurtYear()){
                return@setOnClickListener
            }
            showYear++
            showYear()
            showDay()
        }
    }

    override fun loadData() {
        showYear()
        showMonth()
        showDay()
    }

    @SuppressLint("SimpleDateFormat")
    override fun onViewClick(v: View?) {
        when (v!!.id) {
            R.id.btnDone -> {//提交
                val selectDay = getSelectDay()
                if (selectDay == 0){
                    showNittyToast(context.getString(R.string.dialog_tips_select_birth_error))
                    return
                }
                dismiss()
                var formatDay = "$selectDay"
                if (selectDay < 10){
                    formatDay = "0$selectDay"
                }

                val calendar = Calendar.getInstance()
                calendar.set(Calendar.YEAR, showYear)
                calendar.set(Calendar.MONTH, showMonth-1)
                calendar.set(Calendar.DAY_OF_MONTH, selectDay)
                val obj = JSONObject()
                obj.put("showDate","$formatDay-${NittyDateHelper.getMonthList()[showMonth - 1].optString("month")}-$showYear")
                obj.put("subDate",SimpleDateFormat("yyyy-MM-dd").format(calendar.timeInMillis))
                obj.put("duration",System.currentTimeMillis() - startTime)
                if (mCallback != null){
                    mCallback!!.completed(obj)
                }
            }
        }
    }

    override fun show() {
        super.show()
        startTime = System.currentTimeMillis()
    }

    interface IDialogCallback {
        fun completed(selectDate: JSONObject)
    }

    /**
     * 设置月份
     */
    private fun initMonthTabLayout(){
        binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab!!.setSelected(tab)
            }
            override fun onTabUnselected(tab: TabLayout.Tab?) {
                tab!!.setUnselected()
            }
            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })
    }

    private fun initRvWeek() {
        binding.rvWeek.setHasFixedSize(true)
        binding.rvWeek.isNestedScrollingEnabled = false
        binding.rvWeek.isFocusableInTouchMode = false //不需要焦点
//        val decoration = NittyDensityUtil.dp2px(12f)
//        binding.rvWeek.addItemDecoration(GridSpacingItemDecoration(7,decoration,true))
        val layoutManager = GridLayoutManager(context,7)
        binding.rvWeek.layoutManager = layoutManager
        weekAdapter = WeekAdapter(binding.rvWeek)
        binding.rvWeek.adapter = weekAdapter
        binding.rvWeek.itemAnimator = DefaultItemAnimator()
        weekAdapter!!.data = NittyDateHelper.getWeekList()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initRvDay() {
        binding.rvDay.setHasFixedSize(true)
        binding.rvDay.isNestedScrollingEnabled = false
        binding.rvDay.isFocusableInTouchMode = false //不需要焦点
        val decoration = NittyDensityUtil.dp2px(12f)
        binding.rvDay.addItemDecoration(GridSpacingItemDecoration(7,decoration,true))
        val layoutManager = GridLayoutManager(context,7)
        binding.rvDay.layoutManager = layoutManager
        mDayAdapter = DayAdapter(binding.rvDay)
        binding.rvDay.adapter = mDayAdapter
        binding.rvDay.itemAnimator = DefaultItemAnimator()
        mDayAdapter!!.setOnItemChildClickListener(CommonOnItemChildClickListener { _, childView, position ->
            val item = mDayAdapter!!.getItem(position)
            if (showYear > NittyDateHelper.getCurtYear()){
                return@CommonOnItemChildClickListener
            }
            if (showYear == NittyDateHelper.getCurtYear() && showMonth > NittyDateHelper.getCurtMonth()){
                return@CommonOnItemChildClickListener
            }
            if (showYear == NittyDateHelper.getCurtYear() && showMonth == NittyDateHelper.getCurtMonth() && item.optInt("day") > NittyDateHelper.getCurtDay()){
                return@CommonOnItemChildClickListener
            }
            if (item.optBoolean("isSelect") || item.optInt("day") == 0){
                return@CommonOnItemChildClickListener
            }

            for (i in 0..<mDayAdapter!!.itemCount){
                val obj = mDayAdapter!!.getItem(i)
                obj.put("isSelect",false)
                if (i == position){
                    obj.put("isSelect",true)
                }
            }
            mDayAdapter!!.notifyDataSetChanged()
        })
    }

    /**
     * 选中状态
     */
    fun TabLayout.Tab.setSelected(tab: TabLayout.Tab) {
        if (showYear > NittyDateHelper.getCurtYear()){
            return
        }
        this.customView?.let {
            val textMonth = it.findViewById<MediumTextView>(R.id.textMonth)
            textMonth.setTypeface(NittyApp.app.getBoldTypeface())
            textMonth.setTextColor(Color.parseColor("#FFFFFFFF"))
            textMonth.shapeDrawableBuilder.setSolidColor(Color.parseColor("#FFFD5118")).intoBackground()
        }
        if (!isInit){
            showMonth = tab.position + 1
            showDay()
        }
        isInit = false
    }

    /**
     * 未选中状态
     */
    fun TabLayout.Tab.setUnselected() {
        this.customView?.let {
            val textMonth = it.findViewById<MediumTextView>(R.id.textMonth)
            textMonth.setTypeface(NittyApp.app.getMediumTypeface())
            textMonth.setTextColor(Color.parseColor("#FF666666"))
            textMonth.shapeDrawableBuilder.setSolidColor(Color.parseColor("#00000000")).intoBackground()
        }
    }

    /**
     * 设置年份
     */
    private fun showYear(){
        binding.textYear.text = "$showYear"
    }

    /**
     * 设置月份
     */
    private fun showMonth(){
        binding.tabLayout.removeAllTabs()
        val monthList = NittyDateHelper.getMonthList()
        monthList.forEach {
            it.put("year",showYear)
            val tab = binding.tabLayout.newTab()
            val tabBinding = DialogBirthdayMonthItemBinding.inflate(LayoutInflater.from(context))
            tabBinding.textMonth.text = it.optString("month")
            tab.setCustomView(tabBinding.root)
            binding.tabLayout.addTab(tab)
        }

        val curtIndex = showMonth - 1
        binding.tabLayout.getTabAt(curtIndex)!!.select()
        binding.tabLayout.post {
            binding.tabLayout.setScrollPosition(curtIndex,0f,false)
        }
    }

    /**
     * 设置日期
     */
    private fun showDay(){
        val dayList = arrayListOf<JSONObject>()
        //指定年月的1号是星期几
        val week = NittyDateHelper.getDayOfWeek(showYear,showMonth,1)
        for (i in 0..<week){
            val item  = JSONObject()
            item.put("year",0)
            item.put("month",0)
            item.put("day",0)
            dayList.add(item)
        }
        dayList.addAll(NittyDateHelper.getDayList(showYear,showMonth))
        for (i in 0..<dayList.size){
            val day = dayList[i]
            day.put("isSelect",false)
            if (showYear == NittyDateHelper.getCurtYear() && showMonth == NittyDateHelper.getCurtMonth() && day.optInt("day") == showDay){
                day.put("isSelect",true)
            }
        }
        mDayAdapter!!.data = dayList
    }

    /**
     * 获取选中的日期
     */
    private fun getSelectDay(): Int{
        var day = 0
        for (i in 0..<mDayAdapter!!.itemCount){
            val item = mDayAdapter!!.getItem(i)
            if (item.optBoolean("isSelect")){
                day = item.optInt("day")
                break
            }
        }
        return day
    }

    /**
     * 周
     */
    internal inner class WeekAdapter(recyclerView: RecyclerView?) : CommonRecyclerViewAdapter<JSONObject>(recyclerView, R.layout.dialog_birthday_week_item) {
        override fun setItemChildListener(helper: CommonViewHolderHelper, viewType: Int) {
        }
        override fun fillData(helper: CommonViewHolderHelper, position: Int, model: JSONObject) {
            val textWeek = helper.getView<MediumTextView>(R.id.textWeek)
            textWeek.text = model.optString("week")
        }
    }

    /**
     * 日期
     */
    internal inner class DayAdapter(recyclerView: RecyclerView?) : CommonRecyclerViewAdapter<JSONObject>(recyclerView, R.layout.dialog_birthday_day_item) {
        override fun setItemChildListener(helper: CommonViewHolderHelper, viewType: Int) {
            helper.setItemChildClickListener(R.id.textDay) //点击Item
        }
        override fun fillData(helper: CommonViewHolderHelper, position: Int, model: JSONObject) {
            val textDay = helper.getView<MediumTextView>(R.id.textDay)
            val showDay = model.optInt("day")
            if (showDay == 0){
                textDay.text = ""
            } else {
                textDay.text = "$showDay"
            }

            if (model.optBoolean("isSelect")){
                textDay.setTypeface(NittyApp.app.getBoldTypeface())
                textDay.setTextColor(Color.parseColor("#FFFFFFFF"))
                textDay.shapeDrawableBuilder.setSolidColor(Color.parseColor("#FFFD5118")).intoBackground()
            } else {
                textDay.setTypeface(NittyApp.app.getMediumTypeface())
                textDay.setTextColor(Color.parseColor("#FF000000"))
                textDay.shapeDrawableBuilder.setSolidColor(Color.parseColor("#00000000")).intoBackground()
            }
        }
    }

    override fun onStart() {
        super.onStart()
        NittyEventPointHelper.addEventPointRequestAction(NittyEventPointType.DIALOG.NITTY_DIALOG_BIRTHDAY_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        NittyEventPointHelper.addEventPointRequestAction(NittyEventPointType.DIALOG.NITTY_DIALOG_BIRTHDAY_DISMISS,eventRemark)
    }
}